package com.runen.infinitemovement.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.GetTopIdEntity;
import com.runen.infinitemovement.model.entity.UserEntity;
import com.runen.infinitemovement.tool.AppUtils;
import com.runen.infinitemovement.widget.popupwind.CommonDialog;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.LogUtil;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;

public class LoginActivity2 extends BaseActivity {
    @BindView(R.id.tv_user_agreement)
    TextView tvUserAgreement;
    @BindView(R.id.tv_privacy_agreement)
    TextView tvPrivacyAgreement;
    @BindView(R.id.ll_weixin_login)
    LinearLayout ll_weixin_login;
    @BindView(R.id.ll_phone_login)
    LinearLayout ll_phone_login;
    @BindView(R.id.cb_user_agreement)
    CheckBox cbUserAgreement;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login2;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return false;
    }

    @OnClick({R.id.ll_weixin_login, R.id.ll_phone_login, R.id.tv_user_agreement, R.id.tv_privacy_agreement, R.id.ll_user_agreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_weixin_login:
//                if (!cbUserAgreement.isChecked()) {
//                    ToastUtils.showShort("请先同意用户协议以及隐私政策");
//                    return;
//                }
                onWeiXin();
                break;
            case R.id.ll_phone_login:
                if (!cbUserAgreement.isChecked()) {
                    ToastUtils.showShort("请先同意用户协议以及隐私政策");
                    return;
                }
                startActivity(new Intent(this, LoginActivity.class));
                break;
            case R.id.tv_user_agreement:
                Intent intent = new Intent(this, WebActivity.class);
                intent.putExtra("LINK_URL", Constant.USER_AGREEMENT);
                intent.putExtra("flag", 1);
                startActivity(intent);
                break;
            case R.id.tv_privacy_agreement:
                Intent intent2 = new Intent(this, WebActivity.class);
                intent2.putExtra("LINK_URL", Constant.PRIVACY_AGREEMENT);
                intent2.putExtra("flag", 2);
                startActivity(intent2);
                break;
            case R.id.ll_user_agreement:
                cbUserAgreement.setChecked(!cbUserAgreement.isChecked());
                break;
        }
    }

    private void onWeiXin() {
        Platform plat = ShareSDK.getPlatform(Wechat.NAME);

        if (plat == null) {
            return;
        }
        //判断指定平台是否已经完成授权
//        if (plat.isAuthValid()) {
//            PlatformDb platDB = plat.getDb();//获取数平台数据DB
////                    //通过DB获取各种数据
//            platDB.getToken();
//            platDB.getUserGender();
//            platDB.getUserIcon();
//            platDB.getUserId();
//            platDB.getUserName();
//            String userId = platDB.getUserId();
//            if (userId != null) {
//                LogUtil.e("WEIXIN", userId);
//                onLogin(userId, platDB.getUserIcon(),platDB.getUserName());
//                return;
//            }
//        }
        plat.removeAccount(true); //移除授权状态和本地缓存，下次授权会重新授权
        plat.SSOSetting(false); //SSO授权，传false默认是客户端授权，没有客户端授权或者不支持客户端授权会跳web授权
        plat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int action, HashMap<String, Object> hashMap) {
                //在platform.getDb().exportData()或者hashMap找需要的信息

                //String unionid =platform.getDb().get("unionid”);//微信获取unionid

                String s = platform.getDb().exportData();//

                onLogin(platform.getDb().getUserId(), platform.getDb().getUserIcon(), platform.getDb().getUserName());
                //用户资源都保存到res
                //通过打印res数据看看有哪些数据是你想要的
//                if (action == Platform.ACTION_USER_INFOR) {
//                    PlatformDb platDB = platform.getDb();//获取数平台数据DB
//                    //通过DB获取各种数据
//                    platDB.getToken();
//                    platDB.getUserGender();
//                    platDB.getUserIcon();
//
//                    platDB.getUserName();
//
//
//                    LogUtil.e("WEIXIN", "qqlogin---onComplete: " + s);
//                }
//


            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                LogUtil.e("WEIXIN", "qqlogin---onError: ");
            }

            @Override
            public void onCancel(Platform platform, int i) {

            }
        });
        ShareSDK.setActivity(this);//抖音登录适配安卓9.0
        plat.authorize();//单独授权
    }

    private void onLogin(String userId, String userIcon, String userName) {
        UserAPI.clearLogin();
        Map<String, String> object = new HashMap<>();
        object.put("grant_type", "mobile_code");
        object.put("type", "1");
        object.put("unionId", userId);
        showDialog();
        new UserAPI().onLogin(object, new BaseResultCallback<UserEntity>() {
            @Override
            public void onResponse(UserEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    if (!response.isBound) {
                        Intent intent = new Intent(LoginActivity2.this, AccountBindingActivity.class);
                        intent.putExtra("userIcon", userIcon);
                        intent.putExtra("userId", userId);
                        intent.putExtra("userName", userName);
                        startActivity(intent);
                    } else if (response.isNew) {
                        Intent intent = new Intent(LoginActivity2.this, ImprovePersonalDataActivity.class);
                        intent.putExtra("userIcon", userIcon);
                        intent.putExtra("userName", userName);
                        startActivity(intent);
                    } else if (response.inTenant == 0) {
                        startActivity(new Intent(LoginActivity2.this, InputTeamCodeActivity.class));
                    } else if (response.inTenant == 1) {//判断人员加入部门的状态（0未申请 1审批中 2通过 3拒绝）
                        Intent intent = new Intent(LoginActivity2.this, InputTeamCodeActivity.class);
                        intent.putExtra("BranchCheck", 1);
                        startActivity(intent);
                        finish();
                    } else if (response.inTenant == 2) {
                        UserAPI.saveUserInfo(response);
                        userRegId();
//                        startActivity(new Intent(LoginActivity2.this, MainActivity.class));
//                        finish();
                        AppUtils.jumpToMain(LoginActivity2.this);
                    } else if (response.inTenant == 3) {
                        ToastUtils.showShort("请重新选择部门");
//                        startActivity(new Intent(LoginActivity2.this, CheckJoinUsRecommendActivity.class));
                        startActivity(new Intent(LoginActivity2.this, InputTeamCodeActivity.class));
                    } else if (response.inTenant == 4) {
                        topId();
                    } else if (response.inTenant == 5) {
                        UserAPI.saveUserInfo(response);
                        userRegId();
                        CommonDialog dialog = CommonDialog.getInstance(LoginActivity2.this,
                                "您已被队长踢出团队，加入新团队重新踏上征途吧~");
                        dialog.setCancelable();
                        dialog.setOnClickListener(new CommonDialog.OnClickListener() {
                            @Override
                            public void onSendListener() {
                                topId();
                            }

                            @Override
                            public void onDismiss() {

                            }
                        });
                    } else {
                        UserAPI.saveUserInfo(response);
                    }
                } else {
                    ToastUtils.showShort(response.msg);

                }
            }

            @Override
            public void onError(Throwable e, String body) {
                super.onError(e, body);
                dismissDialog();
            }
        });
    }

    private void userRegId() {
        JSONObject object = new JSONObject();
        String regId = JPushInterface.getRegistrationID(this);
        LogUtil.e("regId", regId);
        if (!TextUtils.isEmpty(regId)) {
            try {
                object.put("channelId", regId);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        new UserAPI().onUserRegId(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                if (response.getCode() != 0) {
                    ToastUtils.showShort(response.getMessage());
                }
            }
        });
    }

    private void topId() {
        showDialog();
        new UserAPI().getTopId(new BaseResultCallback<GetTopIdEntity>() {
            @Override
            public void onResponse(GetTopIdEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    if (!TextUtils.isEmpty(response.data)) {
                        Intent intent = new Intent(LoginActivity2.this, CheckTeamActivity.class);
                        intent.putExtra("companyId", response.data);
                        startActivity(intent);
                    }
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                super.onError(e, body);
                dismissDialog();
            }
        });
    }
}